package com.sts.controller;

import com.sts.common.result.Result;
import com.sts.dto.*;
import com.sts.service.TicketService;
import com.sts.service.TicketStatusFlowService;
import com.sts.service.TicketCommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ticket")
@RequiredArgsConstructor
public class TicketController {

    private final TicketService ticketService;
    private final TicketStatusFlowService ticketStatusFlowService;
    private final TicketCommentService ticketCommentService;

    /* ========== 工单 ========== */

    /** 创建工单：USER/HANDLER/ADMIN 均可 */
    @PostMapping
    @PreAuthorize("hasRole('USER') or hasRole('HANDLER') or hasRole('ADMIN')")
    public Result<TicketDTO> create(@RequestBody TicketCreateDTO dto,
                                    @RequestHeader("X-User-Id") Long creatorId) {
        return Result.success(ticketService.create(dto, creatorId));
    }

    /** 查看工单详情：创建人、被指派人、管理员可见 */
    @GetMapping("/{id}")
//    @PreAuthorize("@ticketSecurity.canAccess(#id, authentication)")
    public Result<TicketDTO> detail(@PathVariable Long id) {
        TicketDTO dto = ticketService.detail(id);
        return dto == null ? Result.error("工单不存在") : Result.success(dto);
    }

    /** 列表：普通用户只看自己；管理员看全部 */
    @GetMapping
    @PreAuthorize("hasRole('USER') or hasRole('HANDLER') or hasRole('ADMIN')")
    public Result<List<TicketDTO>> list(@RequestHeader("X-User-Id") Long userId) {
        List<TicketDTO> list = ticketService.list();
        return Result.success(list);
    }

    /** 指派处理人：仅管理员或当前处理人可指派 */
    @PutMapping("/assign")
    @PreAuthorize("hasRole('ADMIN') or @ticketSecurity.isHandler(#dto.ticketId, authentication)")
    public Result<Void> assign(@RequestBody TicketAssignDTO dto,
                               @RequestHeader("X-User-Id") Long operatorId) {
        ticketService.assign(dto, operatorId);
        return Result.success();
    }

    /** 修改状态：创建人、被指派人、管理员可改 */
    @PutMapping("/status")
//    @PreAuthorize("@ticketSecurity.canUpdateStatus(#dto.ticketId, authentication)")
    public Result<Void> updateStatus(@RequestBody TicketStatusUpdateDTO dto,
                                     @RequestHeader("X-User-Id") Long operatorId) {
        ticketService.updateStatus(dto, operatorId);
        return Result.success();
    }

   /* ========== 状态流转日志 ========== */

    /** 查看流转记录：同工单可见逻辑 */
    @GetMapping("/{id}/flow")
//    @PreAuthorize("@ticketSecurity.canAccess(#id, authentication)")
    public Result<List<TicketStatusFlowDTO>> listStatusFlow(@PathVariable Long id) {
        return Result.success(ticketStatusFlowService.listByTicket(id));
    }
}